package com.mobilesafe.ui;

import java.io.File;
import java.io.IOException;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mobilesafe.R;
import com.mobilesafe.base.BaseActivity;
import com.mobilesafe.domain.UpdateInfo;
import com.mobilesafe.engine.DownLoadFileTask;
import com.mobilesafe.engine.UpdateInfoService;

public class SplashActivity extends BaseActivity {
	private static final String TAG = "SplashActivity";
	private TextView tv_splash_version;
	private LinearLayout ll_splash_main;
	private String versiontext = null;
	private String version;
	private String description ;
	private String apkurl;
	private UpdateInfo info;
	private ProgressDialog pd ;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Log.i(TAG, "弹出来升级对话框");
			showUpdateDialog();
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// 取消标题栏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		// 完成窗体的全屏显示 // 取消掉状态栏
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		versiontext = getVersion();
		new Thread() {

			@Override
			public void run() {
				try {
					sleep(1000);
					
					if (isNeedUpdate(versiontext)) {
						handler.sendEmptyMessage(0);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}.start();
		pd = new ProgressDialog(this);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setMessage("正在下载...");
		findViewById();
		AlphaAnimation aa = new AlphaAnimation(0.0f, 1.0f);
		aa.setDuration(2000);
		ll_splash_main.setAnimation(aa);

	}

	/**
	 * 显示升级对话框
	 */
	private void showUpdateDialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setIcon(R.drawable.app_logo);
		builder.setMessage(description);
		builder.setCancelable(false);
		builder.setPositiveButton("确定", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				Log.i(TAG, "下载apk文件" + apkurl);
				if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
					String sdPath = "/sdcard/MobileSafe/";
					File filepath = new File(sdPath);
					filepath.mkdir();
					DownLoadFileThreadTask task = new DownLoadFileThreadTask(apkurl,"/sdcard/MobileSafe/MobileSafe2.apk");
					pd.show();
					new Thread(task).start();
				}else{
					Log.i(TAG, "sd卡不可用");
					loadMainUI();
				}

			}
		});
		builder.setNegativeButton("取消", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				Log.i(TAG, "取消升级，进入主界面");
				loadMainUI();
			}
		});
		builder.create().show();

	}

	/**
	 * 
	 * @param versiontext:当前客户端的版本号信息
	 * @return 是否需要更新
	 */
	private boolean isNeedUpdate(String versiontext) {
		// TODO Auto-generated method stub
		try {
			UpdateInfoService service = new UpdateInfoService(this);
			UpdateInfo info = service.getUpdataInfo(R.string.updateurl);
			version = info.getVersion();
			Log.i(TAG, "更新版本:"+version);
			description = info.getDescription();
			Log.i(TAG, "更新版本信息:"+description);
			apkurl = info.getApkurl();
			Log.i(TAG, "更新版本url: "+apkurl);
			if (versiontext.equals(version)) {
				Log.i(TAG, "版本相同不必升级，进入主界面！");
				loadMainUI();
				return false;
			} else {
				Log.i(TAG, "版本不相同！");
				return true;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.i(TAG, "获取更新信息异常, 进入主界面");
			loadMainUI();
			return false;
		}

	}

	/**
	 * 加载主页面
	 */
	private void loadMainUI() {
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
		finish(); // 把当前activity从任务栈里面移除
	}

	@Override
	protected void findViewById() {
		// TODO Auto-generated method stub
		tv_splash_version = (TextView) findViewById(R.id.tv_splash_version);
		tv_splash_version.setText(versiontext);
		ll_splash_main = (LinearLayout) findViewById(R.id.ll_splash_main);
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub

	}

	/**
	 * 获得当前应用程序的版本号
	 * 
	 * @return
	 */
	public String getVersion() {
		try {
			PackageManager packageManager = getPackageManager();
			PackageInfo info = packageManager.getPackageInfo(getPackageName(),
					0);
			return info.versionName;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "未知版本";
		}
	}
	
	private class DownLoadFileThreadTask implements Runnable{
		private String path; // 服务器路径
		private String filepath; // 本地文件路径
		public DownLoadFileThreadTask(String path, String filepath) {
			this.path = path;
			this.filepath = filepath;
		}
		@Override
		public void run() {
			try {
				File file = DownLoadFileTask.getFile(path, filepath, pd);
				Log.i(TAG,"下载成功");
				pd.dismiss();
				install(file);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.i(TAG,"下载文件失败");
				pd.dismiss();
				loadMainUI();
			}
			
		}
		/**
		 * 安装apk
		 * @param file
		 */
		private void install(File file){
			Intent intent = new Intent();
			intent.setAction(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
			finish();
			startActivity(intent);
		}
		
	}


}
